<template>
    <div class="layout-confirm">
        <!-- 面包屑导航 -->
        <h2>Submit order</h2>

        <div class="layout-address">
            <!-- 地址 -->
            <div class="order-address">

                <h3>
                    <span>Shipping address</span>
                    <!-- <a @click="$router.push('/order/shipping')">Edit</a> -->
                    <a @click="$router.go(-1)">Edit</a>
                </h3>
                <h4 v-if="addressActive.first_name" v-text="addressActive.first_name"></h4>
                <p v-if="addressActive.phone" v-text="addressActive.phone"></p>
                <p v-if="addressActive.email" v-text="addressActive.email"></p>
                <p v-if="addressActive.street" v-text="addressActive.street"></p>
                <p v-if="addressActive.district" v-text="addressActive.district"></p>
                <p v-text="[addressActive.city, addressActive.state, addressActive.post_code].filter(i => i).join(',')">
                </p>
                <p v-text="addressActive.country"></p>

                <div class="order-address-remote" v-if="pricing.remote_sign">
                    <OrderRemoteSign :post_code="addressActive.post_code" />
                </div>

            </div>

            <!-- 物流选项 -->
            <div class="order-express">
                <h3>Shipping method</h3>
                <div class="order-express-forbid" v-if="forbid">
                    <p v-text="forbid"></p>
                    <!-- <button type="primary" @click="$router.push('/order/shipping')">Edit</button> -->
                    <!-- <a @click="$router.go(-1)">Edit</a> -->
                    <button @click="$router.go(-1)">Edit</button>
                </div>
                <template v-else>
                    <ul class="order-express-list">
                        <li v-for="item in logistics.express" :key="item.no"
                            :class="{ active: item.no == logisticsActive }" @click="logisticsActive = item.no">
                            <i></i>
                            <h4 v-text="item.name + ' shipping'"></h4>
                            <p>
                                <em>{{ item.need_time_min }} - {{ item.need_time_max }}</em>
                                <b>business days</b>
                            </p>
                            <CommonCurrencyRate :price="item.price" />
                        </li>
                    </ul>
                    <div class="order-express-notify">Shipping timeframe excludes production lead time.</div>
                </template>
            </div>
        </div>

        <!-- 购买的产品 -->
        <div class="layout-design">
            <h3>
                <span>Products</span>
                <!-- <a @click="$router.push('/order/product')">Edit</a> -->
                <a @click="$router.go(-2)">Edit</a>
            </h3>
            <OrderProductList :design="product" />
        </div>

        <!-- 侧边栏 -->
        <div class="layout-sidebar" :class="{ fixed: fixedSidebar }">
            <div class="order-sidebar" v-loading="loading">
                <h3>Order breakdown</h3>

                <client-only>
                    <ul class="order-sidebar-info">
                        <!-- 商品价格 -->
                        <li>
                            <span>Production ({{ pricing.count }}piece)</span>
                            <strong v-text="getPriceFormat(pricing.product)"></strong>
                        </li>

                        <!-- 空白模板优惠 -->
                        <li v-if="pricing.blank_off">
                            <span>Blank products 5% off</span>
                            <strong v-text="'- ' + getPriceFormat(pricing.blank_off)"></strong>
                        </li>

                        <!-- 吊牌价格 -->
                        <li v-if="pricing.tag_original">
                            <span type="hangtag">Hang tag</span>
                            <strong v-text="getPriceFormat(pricing.tag_original)"></strong>
                        </li>

                        <!-- 包装价格 -->
                        <li v-if="pricing.pack_original">
                            <span type="packaging">Package bag</span>
                            <strong v-text="getPriceFormat(pricing.pack_original)"></strong>
                        </li>

                        <!-- 用户等级折扣 -->
                        <li v-if="pricing.level_off">
                            <CommonLevelDiscount :level="levelInfo" type="icon|label|diff"
                                                 :other="{ diff: '- ' + getPriceFormat(pricing.level_off) }" />
                        </li>

                        <!-- 样品订单有优惠券 -->
                        <li v-if="!shopId && pricing.coupon_usable.length > 0">
                            <el-select clearable v-model="couponActive" size="mini" style="width: 100px"
                                       placeholder="Coupon" :popper-append-to-body="false">
                                <el-option v-for="item in pricing.coupon_usable" :key="item.id" :value="item.id"
                                           :label="100 - Number(item.discount_value) + '% off'"></el-option>
                            </el-select>
                            <strong v-if="pricing.coupon_discount && pricing.coupon_discount != 100"
                                    v-text="'- ' + getPriceFormat(pricing.coupon_off)"></strong>
                        </li>



                        <!-- 物流费用 -->
                        <li>
                            <span>Shipping</span>
                            <strong v-if="!pricing.shipping">--</strong>
                            <strong v-else v-text="getPriceFormat(pricing.shipping)"></strong>
                        </li>

                        <!-- 税费 -->
                        <li v-show="pricing.tax != 0">
                            <span>Tax</span>
                            <strong v-text="getPriceFormat(pricing.tax)"></strong>
                        </li>
                    </ul>
                </client-only>

                <!-- 统计 -->
                <div class="order-sidebar-total">
                    <span>Total:</span>
                    <small v-text="currency"></small>
                    <em v-text="getPriceFormat(pricing.total)"></em>
                </div>

                <!-- 支付 -->
                <div class="order-sidebar-billing" :disabled="!!forbid">
                    <button @click="paymentOpen()" type="primary">Proceed to payment</button>
                    <a @click="onlySave()"> Save for later</a>
                </div>
            </div>
        </div>

        <!-- 支付中 -->
        <OrderPayment ref="payment" @close="paymentClose($event)" @payBefore="payBefore($event)" />
    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "OrderConfirm",
    layout: "layout-logined",
    data () {
        return {
            order_code: '',
            forbid: '',
            loading: false,
            fixedSidebar: false,
        };
    },
    computed: {
        ...mapState({
            currency: 'currency',
            rate: 'rate',
        }),
        ...mapGetters("order", {
            shopId: "getShopId",
            addressActive: "getAddressActive",
            product: "getProduct",
            pricing: "getPricing",
            discount: "getDiscount",
            logistics: "getLogistics",
        }),

        levelInfo () {
            const pricing = this.pricing || {}
            return {
                user_level: pricing.level_num,
                user_discount: pricing.level_discount,
            }
        },

        // 物流选项
        logisticsActive: {
            get () {
                return this.logistics.active
            },
            set (value) {
                if (this.logistics.active != value) {
                    this.$store.commit("order/SET_LOGISTICS_ACTIVE", value);
                }
            }
        },

        // 选择优惠劵
        couponActive: {
            get () {
                return this.discount.coupon_active || '';
            },
            set (value) {
                if (this.discount.coupon_active != value) {
                    this.$store.commit("order/SET_COUPON_ACTIVE", value);
                    this.resetPrice()
                }
            }
        },
    },
    methods: {

        // 价格格式化
        getPriceFormat (val) {

            const rate = this.rate || 1;
            const value = parseFloat(val * rate / 100) || 0;
            return value.toFixed(2);
        },

        // 生成订单
        async makeOrder (callback) {
            if (!this.order_code) {
                const address = this.addressActive || {};
                const pricing = this.pricing;
                const discount = this.discount;
                const logistics = this.logistics;
                const product = this.product;


                const request = {
                    order_type: this.shopId ? 2 : 1, // int  1 样品订单  2 商店订单
                    logistics_channel_no: logistics.active, // string 物流渠道号
                    logistics_price: pricing.shipping, // int 物流支付价格  单位美分
                    tag_price: pricing.tag_price, // 吊牌价格
                    pack_price: pricing.pack_price, // 包装价格

                    shop_id: this.shopId, // int  商店id 样品订单时传空
                    first_name: address.first_name || "", // string 姓名
                    last_name: "", // string 空
                    country_code: address.country_code || "", // string 国家（国际二字码 标准ISO 3166-2 ）
                    country: address.country || "", // string 国家名称
                    city: address.city || "", // string 城市
                    state: address.state || "", // string  州/省
                    district: address.district || "", // string 区、县（可对应为adress 2）
                    street: address.street || "", // string 街道/详细地址（可对应为adress 1）
                    house_number: "", // string 门牌号
                    company: "", // string 公司名
                    email: address.email || "", // string 邮箱
                    phone: address.phone || "", // string 电话
                    phone2: "", // string 备用电话 可为空
                    post_code: address.post_code || "", // string 邮编
                    certificate_no: "", // string 投保人证件号码  可为空
                    certificate_type: "", // string 投保人证件类型  可为空
                    id_back_url: "", // string 证件背面照URL  可为空
                    id_front_url: "", // string 证件正面照URL  可为空
                    discount_id: discount.coupon_active || 0, // int  折扣券ID
                    commodity_prices: pricing.commodity, // int  商品总价格  单位美分 有小数点向上取整
                    tax_price: pricing.tax, // int 税费   单位美分
                    total_money: pricing.total, // int 订单总金额  单位美分
                    order_item: [], // string  子项序列化 string
                    weight: pricing.weight, //总克重
                    remote_sign: pricing.remote_sign,
                };


                product.map((item) => {
                    request.order_item.push({
                        source: item.source, //商品来源，template|shop
                        design_id: item.design_id, //商品设计id，template时传模板id，shop时传商店商品id，
                        sku: item.sku, // 选中的sku
                        count: item.quantity, // 数量
                        tag_design_id: item.tag_price ? item.tag.id : 0,
                        pack_design_id: item.pack_price ? item.pack.id : 0,
                    });
                });








                this.loading = true;
                const result = await this.$http("Order.addOrder", request);
                if (result.code === 0) {
                    this.order_code = result.data;
                    this.loading = false;
                    if (callback) {
                        callback(result)
                    } else {
                        this.$uxMessage.success("Order saved");
                        this.$router.push("/user/order");
                        return result
                    }
                } else {
                    if (callback) {
                        this.loading = false;
                        callback(result)
                    } else {
                        this.loading = false;
                        this.$uxMessage.error(result.msg || "Failed to save order");
                    }
                }
            } else {
                callback && callback({ data: this.order_code })
            }
        },

        // 只是生成订单
        onlySave () {
            if (this.loading) {
                // 加载中的不管
            } else if (this.forbid) {
                // 禁用的
                this.$uxMessage.error(this.forbid);
            } else {
                this.makeOrder();
            }
        },


        // 打开支付对话框
        paymentOpen () {
            if (this.loading) {
                // 加载中的不管
            } else if (this.forbid) {
                // 禁用的
                this.$uxMessage.error(this.forbid);
            } else {

                const option = {
                    amount: this.pricing.total,
                    codes: this.order_code,
                    action: 'single',
                    product: [],
                    shipping: this.addressActive,
                }
                option.product = this.product.map(item => {
                    return {
                        name: item.title,
                        sku: item.sku,
                        price: parseInt(item.price + item.extra_price + item.pack_price + item.tag_price),
                        count: parseInt(item.quantity)
                    }
                })
                this.$refs.payment.open(option);
            }
        },

        // 支付结束
        paymentClose (status) {
            if (this.order_code) {
                this.$router.push("/user/order");
            }
        },

        // 支付前
        payBefore (option) {
            if (this.order_code && option.codes == this.order_code) {
                // 已经有订单了
                return Promise.resolve({ codes: this.order_code })
            } else {
                return new Promise(resolve => {
                    this.makeOrder(result => {
                        option.codes = this.order_code || ''
                        resolve()
                    }).catch(error => {
                        resolve((error || {}).msg || 'Failed to create order, Please check your network connection!')
                    })
                })
            }
        },

        // 重新获取价格
        resetPrice () {
            this.loading = true;
            this.$store.dispatch("order/setConfirmInit").then(res => {
                this.loading = false;
                this.forbid = '';
            }).catch(error => {
                this.loading = false;
                this.forbid = error.msg || 'Failed to get shipping information'
                this.$uxMessage.error(this.forbid);
            })
        },
        checkHeaderActive () {
            const scrollY = document.documentElement.scrollTop || document.body.scrollTop
            this.fixedSidebar = scrollY >= 88
        },
    },
    created () {
        if (process.client) {
            this.resetPrice();
        }
    },
    mounted () {
        this.checkHeaderActive();
        window.addEventListener('scroll', this.checkHeaderActive)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.checkHeaderActive)
    }
};
</script>
<style lang="scss" scoped>
.layout-confirm {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding-right: 298px;
    padding-bottom: 48px;
    position: relative;
    max-width: 1080px;
    margin: 0 auto;

    &>h2 {
        margin: 40px 0 24px;
        font-size: 32px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
    }

    // &::v-deep {
    //     .dialog-layout.active + .el-loading-mask {
    //         display: none;
    //     }
    // }
}

.layout-content {
    flex: 1;
    margin-right: 12px;
}

.layout-sidebar {
    position: absolute;
    right: 0;
    top: 88px;
    width: 286px;

    .order-sidebar {
        position: absolute;
        right: 0;
        top: 16px;
        width: 286px;
        background: #fff;
        border: 1px solid #e5e5e5;
        border-radius: 8px;
        box-sizing: border-box;
        overflow: hidden;
        z-index: 0;

        &>h3 {
            border-bottom: 1px solid #e5e5e5;
            line-height: 40px;
            font-size: 14px;
            font-family: Roboto-Medium, Roboto;
            font-weight: 500;
            color: #000000;
            padding: 0 14px;
            text-align: center;
        }
    }

    &.fixed {
        position: fixed;
        width: 100vw;
        left: 0;
        top: 60px;
        height: 100px;

        .order-sidebar {
            right: 50%;
            margin-right: -540px;
        }
    }

    .order-sidebar-info {
        padding: 16px;

        &>li {
            display: flex;
            flex-direction: row;
            align-items: flex-start;
            justify-content: space-between;
            line-height: 16px;
            font-size: 14px;
            margin-top: 16px;

            .level-discount {
                font-size: 14px;
                display: flex;
                width: 100%;
                height: 16px;

                &::v-deep span[name='icon'] {
                    width: 14px;
                    height: 14px;
                    background-size: 14px 14px;
                    margin-right: 4px;
                }

                &::v-deep span[name='label'] {
                    margin-left: 0;
                }

                &::v-deep span[name='diff'] {
                    flex: 1;
                    text-align: right;
                    font-weight: normal;
                }
            }

            span {
                font-size: 14px;
                color: #000;
                position: relative;

                &[type='hangtag']::before {
                    content: '';
                    display: inline-block;
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                    vertical-align: top;
                    margin-top: 0px;
                    border-radius: 16px;
                    background-size: 16px 16px;
                    background-position: center center;
                    background-repeat: no-repeat;
                    background-color: #e38c8c;
                    background-image: url(https://img.podpartner.com/static/images-20230202/brand/hangtag-icon.png);
                }

                &[type='packaging']::before {
                    content: '';
                    display: inline-block;
                    width: 16px;
                    height: 16px;
                    margin-right: 4px;
                    vertical-align: top;
                    margin-top: 0px;
                    border-radius: 16px;
                    background-size: 16px 16px;
                    background-position: center center;
                    background-repeat: no-repeat;
                    background-color: #9b89bc;
                    background-image: url(https://img.podpartner.com/static/images-20230202/brand/package-icon.png);
                }
            }

            small {
                flex: 1;
                text-align: right;
                color: #000000;
                font-weight: normal;
                font-size: 12px;
                margin-right: 8px;
            }

            strong {
                color: #000000;
                font-weight: normal;
            }
        }

        .el-select {
            height: 16px;

            &::v-deep {
                .el-input {
                    position: relative;
                    top: -6px;
                }
            }
        }
    }

    .order-sidebar-total {
        position: relative;
        padding: 72px 16px 8px 16px;
        display: flex;
        justify-content: flex-end;
        align-items: flex-end;
        font-size: 20px;
        font-weight: bold;
        color: #000000;
        line-height: 18px;
        height: 26px;
        white-space: nowrap;

        &::before {
            content: '';
            position: absolute;
            left: 16px;
            bottom: 0;
            right: 16px;
            height: 1px;
            background-color: #dcdcdc;
        }

        span {
            width: 100%;
            font-size: 16px;
            font-weight: bold;
            color: #000000;
            line-height: 18px;
            position: absolute;
            left: 16px;
            top: 48px;
        }

        small {
            vertical-align: bottom;
            font-size: 14px;
            font-weight: bold;
            color: #000000;
            line-height: 16px;
            position: relative;
            top: -3px;
            margin-right: 4px;
        }

        em {
            font-size: 24px;
            font-weight: bold;
            color: #000000;
            line-height: 26px;
        }
    }

    .order-sidebar-billing {
        margin-left: 16px;
        margin-right: 16px;
        padding-top: 16px;
        display: flex;
        flex-direction: column;

        button {
            height: 40px;
        }

        a {
            height: 18px;
            margin-top: 16px;
            margin-bottom: 18px;
            cursor: pointer;
            text-decoration: underline;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #555555;

            &:hover {
                color: #ea4c89;
            }
        }

        &[disabled] button {
            background: #f6f6f6;
            border-color: #dcdcdc;
            color: #919191;

            &:hover {
                background: #fafafa;
                color: #666;
            }
        }

        &[disabled] a {
            color: #666;
        }
    }
}

.layout-address {
    display: flex;
}

.order-address {
    box-sizing: border-box;
    position: relative;
    padding: 60px 24px 54px;
    background: #fff;
    border-radius: 8px;
    margin-right: 12px;
    flex: 446;
    max-width: 542px;
    border: 1px solid #e5e5e5;
    display: flex;
    flex-direction: column;
    justify-content: center;

    &>h3 {
        position: absolute;
        top: 0;
        left: 0;
        box-sizing: border-box;
        width: 100%;
        line-height: 40px;
        padding-left: 14px;
        border-bottom: 1px solid #e5e5e5;
        display: flex;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        white-space: nowrap;

        a {
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #087196;
            margin-left: 4px;
            cursor: pointer;

            &:hover {
                text-decoration: underline;
                color: #287e9c;
            }
        }
    }

    h4 {
        font-size: 18px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 26px;
        text-overflow: -o-ellipsis-lastline;
        overflow: hidden; //溢出内容隐藏
        text-overflow: ellipsis; //文本溢出部分用省略号表示
        display: -webkit-box; //特别显示模式
        -webkit-line-clamp: 2; //行数
        line-clamp: 2;
        -webkit-box-orient: vertical; //盒子中内容竖直排列
        word-wrap: break-word;
        margin-bottom: 20px;
    }

    p {
        font-size: 14px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000000;
        line-height: 18px;

        &+p {
            margin-top: 16px;
        }
    }

    &>.order-address-remote {
        height: 40px;

        &>.remote-sign {
            position: absolute;
            bottom: 0;
            left: 12px;
            right: 12px;
            padding: 10px 0;
        }
    }
}

.order-express {
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex: 348;
    box-sizing: border-box;
    background: #fff;
    border-radius: 8px;
    border: 1px solid #e5e5e5;
    position: relative;

    &>h3 {
        height: 40px;
        border-bottom: 1px solid #e5e5e5;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 40px;
        padding: 0 14px;
    }

    .order-express-forbid {
        flex: 1;
        padding: 16px;

        p {
            font-size: 16px;
            padding: 16px;
            background: rgba(253, 228, 226, 0.25);
            border-top: 1px dashed #f44336;
            border-bottom: 1px dashed #f44336;
            font-weight: normal;
            color: #f44336;
            line-height: 20px;
        }

        button {
            margin-top: 16px;
            width: 120px;
            height: 32px;
        }
    }

    .order-express-list {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        padding: 14px;

        li {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            position: relative;
            cursor: pointer;
            background: transparent;
            border-radius: 8px;
            padding: 10px 10px 10px 36px;
            transition: all 0.2s;

            &>i {
                position: absolute;
                left: 10px;
                top: 14px;
                width: 14px;
                height: 14px;
                border-radius: 9px;
                border: 2px solid #737373;
                transition: border 0.2s;

                &:after {
                    content: '';
                    position: absolute;
                    left: 50%;
                    top: 50%;
                    width: 6px;
                    height: 6px;
                    background: #ea4c89;
                    border-radius: 9px;
                    opacity: 0;
                    transform: translate(-50%, -50%);
                    transition: opacity 0.2s;
                }
            }

            &>.currency-rate {
                font-size: 14px;
                color: #000;
                line-height: 28px;
            }

            &+li {
                margin-top: 10px;
            }

            &:hover {
                background: #f8f8f8;
            }

            &.active {
                cursor: default;
                background: none;

                &>i {
                    border-color: #ea4c89;

                    &:after {
                        opacity: 1;
                    }
                }
            }
        }

        h4 {
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 18px;
            margin-bottom: 8px;
        }

        p {
            font-size: 14px;
            color: #000;
            line-height: 16px;
            font-family: Roboto-Regular, Roboto;
            color: #555;

            em {
                font-style: normal;
            }

            b {
                font-weight: inherit;
            }
        }

        .currency-rate {
            font-family: Roboto-Regular, Roboto;
            color: #555;

            &::v-deep span {
                color: #555;
            }
        }
    }

    .order-express-notify {
        margin: 0 12px;
        padding: 10px 0;
        font-size: 12px;
        font-family: Roboto-Regular, Roboto;
        font-weight: 400;
        color: #000;
        line-height: 18px;
        border-top: 1px dashed #e6e6e6;

        &::before {
            content: '*';
            color: #c62828;
            margin-right: 2px;
        }
    }
}

.layout-design {
    margin-top: 28px;

    &>h3 {
        line-height: 20px;
        display: flex;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        margin-bottom: 16px;

        a {
            font-size: 12px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #087196;
            margin-left: 4px;
            cursor: pointer;

            &:hover {
                text-decoration: underline;
                color: #287e9c;
            }
        }
    }

    .order-design {
        &::v-deep>h3 {
            display: none;
        }
    }
}
</style>
